"""
菜单管理API
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.extensions import db
from app.models import Menu

menus_bp = Blueprint('menus', __name__, url_prefix='/api/menus')


@menus_bp.route('/all', methods=['GET'])
@jwt_required()
def get_all_menus():
    """获取所有菜单（树形结构）"""
    try:
        # 获取所有一级菜单
        parent_menus = Menu.query.filter_by(parent_id=None, is_active=True)\
                                .order_by(Menu.sort_order).all()
        
        menus = [menu.to_dict() for menu in parent_menus]
        
        return jsonify({'menus': menus}), 200
        
    except Exception as e:
        return jsonify({'message': f'获取菜单列表失败: {str(e)}'}), 500


@menus_bp.route('', methods=['GET'])
@jwt_required()
def get_menus():
    """获取菜单列表（平铺）"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 50, type=int)
        search = request.args.get('search', '')
        
        query = Menu.query
        
        if search:
            query = query.filter(Menu.name.contains(search))
        
        pagination = query.order_by(Menu.sort_order).paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        menus = [menu.to_dict(False) for menu in pagination.items]
        
        return jsonify({
            'menus': menus,
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page,
            'per_page': per_page
        }), 200
        
    except Exception as e:
        return jsonify({'message': f'获取菜单列表失败: {str(e)}'}), 500


@menus_bp.route('', methods=['POST'])
@jwt_required()
def create_menu():
    """创建菜单"""
    try:
        data = request.get_json()
        name = data.get('name')
        path = data.get('path')
        icon = data.get('icon')
        parent_id = data.get('parent_id')
        sort_order = data.get('sort_order', 0)
        
        if not name:
            return jsonify({'message': '菜单名称不能为空'}), 400
        
        # 验证父菜单
        if parent_id:
            parent = Menu.query.get(parent_id)
            if not parent:
                return jsonify({'message': '父菜单不存在'}), 400
        
        menu = Menu(
            name=name,
            path=path,
            icon=icon,
            parent_id=parent_id,
            sort_order=sort_order,
            is_active=data.get('is_active', True)
        )
        
        db.session.add(menu)
        db.session.commit()
        
        return jsonify({
            'message': '菜单创建成功',
            'menu': menu.to_dict(False)
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'创建菜单失败: {str(e)}'}), 500


@menus_bp.route('/<int:menu_id>', methods=['PUT'])
@jwt_required()
def update_menu(menu_id):
    """更新菜单"""
    try:
        menu = Menu.query.get(menu_id)
        if not menu:
            return jsonify({'message': '菜单不存在'}), 404
        
        data = request.get_json()
        
        # 更新基本信息
        if 'name' in data:
            menu.name = data['name']
        if 'path' in data:
            menu.path = data['path']
        if 'icon' in data:
            menu.icon = data['icon']
        if 'sort_order' in data:
            menu.sort_order = data['sort_order']
        if 'is_active' in data:
            menu.is_active = data['is_active']
        
        # 更新父菜单
        if 'parent_id' in data:
            parent_id = data['parent_id']
            if parent_id and parent_id != menu.id:  # 防止设置自己为父菜单
                parent = Menu.query.get(parent_id)
                if not parent:
                    return jsonify({'message': '父菜单不存在'}), 400
                menu.parent_id = parent_id
            else:
                menu.parent_id = None
        
        db.session.commit()
        
        return jsonify({
            'message': '菜单更新成功',
            'menu': menu.to_dict(False)
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'更新菜单失败: {str(e)}'}), 500


@menus_bp.route('/<int:menu_id>', methods=['DELETE'])
@jwt_required()
def delete_menu(menu_id):
    """删除菜单"""
    try:
        menu = Menu.query.get(menu_id)
        if not menu:
            return jsonify({'message': '菜单不存在'}), 404
        
        # 检查是否有子菜单
        if menu.children:
            return jsonify({'message': '该菜单下还有子菜单，无法删除'}), 400
        
        db.session.delete(menu)
        db.session.commit()
        
        return jsonify({'message': '菜单删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'删除菜单失败: {str(e)}'}), 500